package com.justech.eat.util.validator;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * @program: eat-service
 * @description:
 * @author: feifei.li
 * @create: 2020-06-01 10:37
 **/
public class RadioConstraintValidator implements ConstraintValidator<Radio, Object> {
    Radio radio;

    /**
     * Initializes the validator in preparation for
     * {@link #isValid(Object, ConstraintValidatorContext)} calls.
     * The constraint annotation for a given constraint declaration
     * is passed.
     * <p>
     * This method is guaranteed to be called before any use of this instance for
     * validation.
     * <p>
     * The default implementation is a no-op.
     *
     * @param constraintAnnotation annotation instance for a given constraint declaration
     */
    @Override
    public void initialize(Radio constraintAnnotation) {
        this.radio = constraintAnnotation;
    }

    /**
     * Implements the validation logic.
     * The state of {@code value} must not be altered.
     * <p>
     * This method can be accessed concurrently, thread-safety must be ensured
     * by the implementation.
     *
     * @param value   object to validate
     * @param context context in which the constraint is evaluated
     * @return {@code false} if {@code value} does not pass the constraint
     */
    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (value != null) {
            String[] values = this.radio.values();
            boolean in = false;
            for (String s : values) {
                if (value != null) {
                    if (s.equals(value.toString())) {
                        in = true;
                    }
                }
            }
            return in;
        }
        return true;
    }
}
